import Request  from '../../common/utils/Request';
import {Storage} from '../../common/utils/Common';
import prompt from '@system.prompt';
import router from '@ohos.router';
import dataStorage from '@ohos.data.storage';
import featureAbility from '@ohos.ability.featureAbility';
//login js
export default {
    data: {
        // 用户名
        username: "",
        // 密码
        password: "",
        // 是否允许登录
        loginDisabled: true
    },
    changeUsername(val) {
        this.username = val.value;
        this.validate();
    },
    changePassword(val) {
        this.password = val.value;
        this.validate();
    },
    /**
     * 校验判断按钮是否能够使用
     */
    validate() {
      this.loginDisabled = this.username.trim() === '' || this.password.trim() === '';
    },
    async login() {
        let data = {
            username: this.username,
            password: this.password
        }
        let result = await Request.build('/login').post(data);
        let token = result.getHeader().Authorization;
        if (token != null && token != undefined) {
            let storage = await new Storage('user');
            storage.put('token', JSON.stringify(token));
            storage.put('userMsg', result.getData());
            // 显示登录成功消息
            prompt.showToast({
                message: '登录成功',
                duration: 1500,
                bottom: 350
            });
            // 返回页面
            router.push({
                url: 'pages/index/index'
            });

//            featureAbility.getContext().getFilesDir().then((path) => {
//                let storage = dataStorage.getStorageSync(path + '/user')
//                // 此处 token 可能是个对象，因此用 JSON#stringify 强行转 string 否则无法存储
//                storage.putSync('token', JSON.stringify(token));
//                storage.flushSync();
//            });
        }
    }
}
